package frans

import (
	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
	"reflect"
)

//新实例
type Frans struct {
	*echo.Echo
	g  *echo.Group
	db interface{}
}

//战斗>>>
func Fighting() *Frans {
	e := &Frans{Echo: echo.New()}

	e.Use(middleware.Logger())
	e.Use(middleware.Recover())

	return e
}

//自定义^_^^_^中间件
func (this *Frans) Attach(f Onion) *Frans {
	this.Use(f.Process)
	return this
}

//控制器$$$
func (this *Frans) Action(group string, classes ...IClass) *Frans {
	this.g = this.Group(group)
	for _, clazz := range classes {
		clazz.Route(this.g) // 遍历所有IController的具体实现， 并注册Route  这才是关键 !!!

		//TODO: 采用反射注入到控制器中， 控制器中第一个嵌入属性，必须是DB
		vClass := reflect.ValueOf(clazz).Elem()
		if vClass.NumField() > 0 {
			if this.db != nil {
				vClass.Field(0).Set(reflect.New(vClass.Field(0).Type().Elem()))
				vClass.Field(0).Elem().Set(reflect.ValueOf(this.db).Elem())
			}
		}
	}

	return this
}

//设置数据库链接对象
func (this *Frans) DB(db interface{}) *Frans {
	this.db = db
	return this
}

//跑起来...
func (this *Frans) Running(ip string) {
	this.Logger.Fatal(this.Start(ip))
}
